package cn.zysuyuan.auth.controller;

import cn.zysuyuan.auth.client.RoleClient;
import cn.zysuyuan.auth.config.JwtProperties;
import cn.zysuyuan.auth.entity.UserInfo;
import cn.zysuyuan.auth.service.AuthService;
import cn.zysuyuan.auth.utils.JwtUtils;
import cn.zysuyuan.common.entity.Constant;
import cn.zysuyuan.common.entity.R;
import cn.zysuyuan.common.exception.CommonException;
import cn.zysuyuan.common.utils.BeanMapUtils;
import cn.zysuyuan.common.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.util.HashMap;
import java.util.Map;

/**
 * @author flypig
 * @version 1.0
 * @date 2019-11-26 2:03
 */

@Controller
@EnableConfigurationProperties(JwtProperties.class) // 启用配置类
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RoleClient roleClient;

    @PostMapping("accredit")
    @ResponseBody
    public ResponseEntity<String> accredit(
            @RequestParam(value = "username", required = false) String uName,
            @RequestParam(value = "password", required = false) String uPass,
            HttpServletRequest request,
            HttpServletResponse response) {

        String token = this.authService.accredit(uName,uPass);

        if (StringUtils.isBlank(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

//        CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire()*60);

        return ResponseEntity.ok(token);
    }

    @GetMapping("verify")
    public ResponseEntity<Map<String,Object>> verify(
//            @CookieValue("ZY_TOKEN") String token,
            HttpServletRequest request,
            HttpServletResponse response) {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            Map<String,Object> map = new HashMap<>();
            map.put("code", Constant.ERROR_CODE);
            map.put("msg","缺少必要认证信息");
            return  ResponseEntity.ok(map);
        }
        try {
            // 通过jwt工具类使用公钥解析jwt
            UserInfo userInfo = JwtUtils.getInfoFromToken(token,this.jwtProperties.getPublicKey());
            if (userInfo == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            // 刷新jwt中的有效时间
            token =  JwtUtils.generateToken(userInfo,this.jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());

            // 刷新cookie中的有效时间, 指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire()*60,null,true);

            // 返回用户的权限
            Map<String,Object> map = roleClient.findRoles(userInfo.getLevel(),userInfo.getId());
            Map<String,Object> result = BeanMapUtils.beanToMap(userInfo);
            result.put("roles", map);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    @PostMapping("logout")
    @ResponseBody
    public R logout(
            HttpServletRequest request,
            HttpServletResponse response) {
        String token = request.getHeader("token");
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token,this.jwtProperties.getPublicKey());
            if (userInfo == null) {
                return R.error("退出登录失败！");
            }
            // 刷新jwt中的有效时间
            token =  JwtUtils.generateToken(userInfo,this.jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());
            CookieUtils.setCookie(request,response,this.jwtProperties.getCookieName(),token,this.jwtProperties.getExpire()*60);
            Map<String, Object> map = new HashMap<>();
            map.put("code",Constant.SUCCEED_CODE);
            map.put("msg","退出登录成功！");
            return  R.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }
}
